<template>
  <div class="content">
    <van-form validate-first @submit="onSubmit" @failed="onFailed">
      <div
        style="
          color: red;
          line-height: 30px;
          font-size: 12px;
          margin-left: -60px;
        "
      >
        请上传学员身份证正面，上传完毕学员信息将自动填充
      </div>
      <van-field name="uploader" label="身份证">
        <template #input>
          <van-uploader
            v-model="idcardFileList"
            @delete="deleteImgIdcard"
            :after-read="afterReadIdcard"
            :max-count="1"
          />
        </template>
      </van-field>

      <div
        class="input-idCard"
        style="
          position: relative;
          display: flex;
          justify-content: start;
          align-items: center;
        "
      >
        <div
          class="label-idCard"
          @click="showIdTypePicker = true"
          style="font-size: 12px; margin-left: 10px"
        >
          {{ form.docType === "1" ? "大陆身份证" : "港澳身份证" }}
          <van-icon name="arrow-down" />
          <span class="icon">*</span>
        </div>
        <van-popup v-model="showIdTypePicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="docType"
            @confirm="onDocTypeConfirm"
            @cancel="showIdTypePicker = false"
          />
        </van-popup>
        <div style="margin-left: 10px">
          <van-field
            class="no-label"
            v-model="form.customerIdentityCard"
            name="customerName"
            placeholder="请输入学员身份证"
            :rules="[
              { validator, message: '身份证号码格式不正确', require: true },
            ]"
          />
        </div>
      </div>
      <van-field
        clearable
        v-model="form.customerPhone"
        name="customerPhone"
        label="学员电话"
        placeholder="请输入学员电话"
        :rules="[{ required: true, message: '请输入学员电话' }]"
        class="required"
        @blur="fetchCoupon"
      />
      <van-field
        clickable
        clearable
        v-model="form.customerName"
        name="customerName"
        label="学员姓名"
        placeholder="请输入学员姓名"
        :rules="[{ required: true, message: '请填写用户名' }]"
        class="required"
      />
      <van-field
        readonly
        clearable
        name="schoolId"
        :value="schoolName"
        label="校 区"
        placeholder="点击选择校区"
        @click="showPicker = true"
        :rules="[{ required: true, message: '请选择校区' }]"
        class="required"
      />
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="schoolList"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        clearable
        readonly
        name="couponId"
        :value="goodsName"
        label="商 品"
        :placeholder="!form.schoolId ? '请先选择校区' : '点击选择商品'"
        @click="showGoodsPicker = !form.schoolId ? false : true"
        :disabled="!form.schoolId"
        @change="handleGoods"
        :rules="[{ required: true, message: '请选择商品' }]"
        class="required"
      />
      <van-popup v-model="showGoodsPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="goodsList"
          @confirm="onGoodsConfirm"
          @cancel="showGoodsPicker = false"
        />
      </van-popup>
      <van-field
        v-model="form.goodsPrice"
        name="goodsPrice"
        label="商品金额"
        placeholder="请输入商品金额"
        :rules="[{ required: true, message: '请填写商品金额' }]"
        :disabled="true"
        class="required"
      />
      <van-field
        readonly
        :clearable="true"
        name="coupon"
        :value="couponName"
        label="优惠券"
        :placeholder="!form.customerPhone ? '请输入学员手机号' : '请选择优惠券'"
        no-data-text="暂无可使用的优惠券"
        @click="showCouponPicker = !form.schoolId ? false : true"
        :disabled="!form.customerPhone || !goodsName"
        @change="handleCoupon"
        @clear="handleClear"
      />
      <van-popup v-model="showCouponPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="
            couponList.length > 0
              ? couponList
              : [{ text: '暂无数据', value: '' }]
          "
          @confirm="onCouponConfirm"
          @cancel="onCancel"
        />
      </van-popup>
      <van-field
        v-model="form.subAmount"
        name="orderPrice"
        label="优惠券金额"
        placeholder="请输入优惠券金额"
        :disabled="true"
      />
      <van-field
        v-model="form.orderPrice"
        name="orderPrice"
        label="订单金额"
        placeholder="请输入订单金额"
        :rules="[{ required: true, message: '请填写订单金额' }]"
        :disabled="true"
        class="required"
      />
      <van-field
        v-model="form.actualAmount"
        name="actualAmount"
        label="实付金额"
        placeholder="请输入实付金额"
        :rules="[{ required: true, message: '请填写实付金额' }]"
        class="required"
      />
      <van-field
        clearable
        v-model="form.remark"
        name="remark"
        label="备注"
        placeholder="请输入备注"
      />
      <van-field
        clearable
        v-model="form.customerService"
        name="customerService"
        label="业务员"
        placeholder="请输入业务员"
        :rules="[{ required: true, message: '请填写业务员' }]"
        class="required"
      />
      <van-field
        clearable
        v-model="form.customerServicePhone"
        name="customerServicePhone"
        label="业务员电话"
        placeholder="请输入业务员电话"
        :rules="[{ required: true, message: '请填写业务员电话' }]"
        class="required"
      />
      <van-field
        v-if="isShow"
        clearable
        readonly
        name="carModel"
        :value="carModelName"
        label="车 型"
        :placeholder="!form.goodsId ? '请先选择商品' : '点击选择车型'"
        @click="showCarmodelPicker = true"
        :disabled="!form.goodsId"
        class="required"
      />
      <van-popup v-model="showCarmodelPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="carModel"
          @confirm="onCarmodelConfirm"
          @cancel="showCarmodelPicker = false"
        />
      </van-popup>
      <van-field
        clearable
        readonly
        name="payState"
        :value="payStateName"
        label="是否全款"
        placeholder="是否全款"
        @click="showIsPayPicker = true"
        :rules="[{ required: true, message: '请选择是否全款' }]"
        class="required"
      />
      <van-popup v-model="showIsPayPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="payState"
          @confirm="onIsPayConfirm"
          @cancel="showIsPayPicker = false"
        />
      </van-popup>
      <van-field
        clearable
        readonly
        name="payType"
        :value="payTypeName"
        label="支付类型"
        :placeholder="form.payStatus ? '请选择支付类型' : '请选择是否全款'"
        :rules="[{ required: true, message: '请选择支付类型' }]"
        @click="showPayTypePicker = true"
        class="required"
      />
      <van-popup v-model="showPayTypePicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="payType"
          @confirm="onPayTypeConfirm"
          @cancel="showPayTypePicker = false"
        />
      </van-popup>
      <div @click="previewImg" v-if="isShowQrcode">
        <img class="image" src="@/assets/img/pay.jpg" alt="" />
      </div>
      <div class="upload-pay">
        <van-field name="fileIds" label="支付凭证" class="required">
          <template #input>
            <van-uploader
              v-model="uploader"
              @delete="deleteImg"
              :after-read="afterRead"
            />
          </template>
        </van-field>
        <div
          style="
            color: red;
            line-height: 30px;
            font-size: 12px;
            margin-left: -180px;
          "
        >
          请上传学员支付凭证、支付截图
        </div>
      </div>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import Vue from "vue";
import { Toast } from "vant";

import { ImagePreview } from "vant";

Vue.use(Toast);
import Upload from "@/components/Upload";
// import Upload from "@/components/Upload.vue";
import {
  getSchoolList,
  getGoodsList,
  createOrder,
  uploadFile,
  idCard,
  getUserInfo,
  getCoupon,
} from "@/api/index";
export default {
  components: {
    Upload,
    ImagePreview,
  },
  data() {
    return {
      show: false,
      images: [require("../assets/img/pay.jpg")],
      value1: "",
      // 车型
      carModels: [
        {
          value: "1",
          text: "C1",
        },
        {
          value: "2",
          text: "C2",
        },
        {
          value: "3",
          text: "B1",
        },
        {
          value: "4",
          text: "B2",
        },
        {
          value: "5",
          text: "A1",
        },
        {
          value: "6",
          text: "A3",
        },
        {
          value: "7",
          text: "D",
        },
      ],
      // 是否全款
      payState: [
        {
          value: "1",
          text: "是",
        },
        {
          value: "2",
          text: "否",
        },
      ],
      // 支付类型
      payType: [
        {
          value: "2",
          text: "现金",
        },
        {
          value: "3",
          text: "广州码",
        },
        {
          value: "4",
          text: "汇来米",
        },
        {
          value: "6",
          text: "其他",
        },
      ],
      // 优惠券列表
      couponList: [],
      form: {
        customerName: "",
        qty: 1,
        payType: null,
        payStatus: null,
        goodsId: null,
        carModel: null,
        docType: "1",
        couponIds: null,
      },
      schoolList: [],
      goodsList: [],
      showPicker: false,
      showGoodsPicker: false, //商品弹窗
      showCarmodelPicker: false, //车型弹窗
      showIdTypePicker: false, //身份证类型弹窗
      showIsPayPicker: false, //是否全款弹窗
      showPayTypePicker: false, //支付类型弹窗
      showCouponPicker: false, //优惠券弹窗
      schoolName: "",
      goodsName: "",
      carModelName: "",
      payStateName: "",
      payTypeName: "",
      couponName: "",
      // 身份证图片
      idcardFileList: [],
      // 已上传的身份证图
      idcardList: [],
      uploader: [],
      // 已上传的图片
      uploaderList: [],
      fileIds: [],
      filePayIds: [],
      goodsDetails: {}, //商品详情
      carModel: [],
      isShow: false, //车型显示隐藏
      docType: [
        {
          text: "大陆身份证",
          value: "1",
        },
        {
          text: "港澳身份证",
          value: "0",
        },
      ],
      validate: false, //校验
      flag: false, //是否显示
      isSelectSpecialSchool: false,
      isSelectOtherPayType: false,
      isShowQrcode: false,
    };
  },
  watch: {
    "form.goodsId"(value) {
      this.carModelName = "";
      this.carModel = [];
      this.isShow = false;
      if (this.form.carModel) {
        this.form.carModel = null;
      }
      this.goodsList.forEach((item) => {
        if (item.value === this.form.goodsId) {
          this.goodsDetails = item;
          if (this.goodsDetails) {
            this.goodsDetails.carModelData.forEach((item1) => {
              this.carModels.forEach((item2) => {
                if (item1 === item2.value) {
                  this.carModel.push(item2);
                }
              });
            });
          }
          if (this.carModel.length === 1) {
            this.form.carModel = this.carModel[0].value;
          }
          this.isShow = this.carModel.length > 1 ? true : false;
        }
      });
    },
  },
  created() {
    var searchParams = new URLSearchParams(window.location.search);
    let data = window.location.href.split("?")[1].split("=")[1];
    if (data) {
      localStorage.setItem("token", data);
      this.fetchSchoolList();
    }

    // localStorage.setItem(
    //   "token",
    //   "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjQ5YzcxZWZjLWE5YjgtNDk0MC05YTZjLTY3MWM2NzdkYmZiOSJ9.OddoQDzu99RvU1J4A7oHIDzs3bTG7C8uPc-uAvp3sLzuj1ZQ0sewr1GIoF_dOBAHOkl210Jk55GNuXkeDy0Vhw"
    // );
    // this.fetchSchoolList();

    // Toast('token',token)
  },

  methods: {
    // 图片预览
    previewImg() {
      ImagePreview(this.images);
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      switch (this.form.docType) {
        case "1":
          var reg =
            /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
          return reg.test(val);
        case "0":
          var reg = /^([A-Z]\d{6,10}(\(\w{1}\))?)$/;
          return reg.test(val);
        default:
          break;
      }
    },
    // 获取个人信息
    getUserInfoByPhone() {
      if (this.form.customerPhone) {
        Toast.loading({
          duration: 0,
          message: "加载中...",
          forbidClick: true,
        });
        getUserInfo(this.form.customerPhone).then((res) => {
          if (res.data.code === 200) {
            this.form.customerIdentityCard = res.data.data.customerIdentityCard;
            this.form.customerName = res.data.data.customerName;
            Toast.clear();
          } else {
            Toast.fail(res.data.msg);
            setTimeout(() => {
              Toast.clear();
            }, 2000);
          }
        });
      }
    },
    // 删除身份证图片
    deleteImgIdcard(file) {
      this.idcardList.map((item, index) => {
        if (item.name === file.file.name) {
          this.idcardList.splice(index, 1);
          // this.filePayIds.splice(index, 1);
          // this.form.fileIds = this.filePayIds;
        }
      });
    },
    // 身份证上传前压缩操作
    beforeReadIdcard(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          const img = new Image();
          console.log("event", e);
          img.src = e.target.result;
          img.onload = () => {
            console.log("压缩");
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");
            canvas.width = 400; // 设置压缩后图片的宽度
            canvas.height = 400 * (img.height / img.width); // 根据原图比例计算高度
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            canvas.toBlob(
              (blob) => {
                const compressedFile = new File([blob], file.name, {
                  type: file.type,
                });
                resolve(compressedFile);
              },
              file.type,
              0.9
            ); // 压缩质量为 0.9
          };
        };
      });
    },
    // 上传身份证图
    afterReadIdcard(file) {
      Toast.loading({
        duration: 0,
        message: "加载中...",
        forbidClick: true,
      });
      console.log("file", file);

      this.beforeReadIdcard(file.file).then((response) => {
        console.log("res", response);
        //定义formData
        const formData = new FormData();
        formData.append("files", file.file); // 传入文件
        formData.append("type", 2);
        this.idcardList.push(file.file);
        //调用请求
        uploadFile(formData)
          .then((res) => {
            if (res.data.data) {
              idCard(res.data.data).then((res) => {
                if (res.data.code === 200) {
                  this.form.customerIdentityCard = res.data.data.idcard;
                  this.form.customerName = res.data.data.name;

                  Toast.clear();
                } else {
                  Toast.fail(res.data.msg);
                  setTimeout(() => {
                    Toast.clear();
                  }, 2000);
                }
              });
            }
          })
          .catch((error) => {});
      });
    },
    //  上传支付凭证
    afterRead(file) {
      Toast.loading({
        duration: 0,
        message: "加载中...",
        forbidClick: true,
      });
      //定义formData
      const formData = new FormData();
      formData.append("files", file.file); // 传入文件
      formData.append("type", 2);
      this.uploaderList.push(file.file);
      //调用请求
      uploadFile(formData)
        .then((res) => {
          this.filePayIds.push(res.data.data[0]);
          this.form.fileIds = this.filePayIds;
          Toast("上传成功");
          Toast.clear();
          console.log("res", this.form.fileIds);
        })
        .catch((error) => {});
    },
    // 删除支付凭证
    deleteImg(file) {
      // 匹配fileList的项的fileName，相同的话把filesId对应删除
      this.uploaderList.map((item, index) => {
        if (item.name === file.file.name) {
          this.uploaderList.splice(index, 1);
          this.filePayIds.splice(index, 1);
          this.form.fileIds = this.filePayIds;
        }
      });
      console.log("index", this.uploader, this.form.fileIds);
    },

    // 获取校区列表
    fetchSchoolList() {
      getSchoolList().then((res) => {
        let list = res.data.data;
        // 遍历 list，将数据放入 schoolList
        if (res.data.data) {
          list.forEach((item) => {
            this.schoolList.push({
              value: item.id,
              text: item.name,
            });
          });
        }
      });
    },
    // 根据校区获取商品列表
    fetchGoodsList() {
      if (this.form && this.form.schoolId) {
        getGoodsList(this.form.schoolId).then((res) => {
          let list = res.data.data;
          if (res.data.data) {
            list.forEach((item) => {
              this.goodsList.push({
                value: item.id,
                text: item.name,
                price: item.price,
                carModelData: item.carModelData,
              });
            });
          }
        });
      }
    },
    // 选择身份证类型
    onDocTypeConfirm(item) {
      this.form.docType = item.value;
      this.showIdTypePicker = false;
    },
    // 选择校区
    onConfirm(item) {
      this.schoolName = item.text;
      this.form.schoolId = item.value;
      this.showPicker = false;

      const specialSchoolsReg = /(大岗|鱼窝头|东涌|黄阁)/gi;
      if (specialSchoolsReg.test(this.schoolName)) {
        this.isSelectSpecialSchool = true;
        if (this.isSelectOtherPayType) {
          this.isShowQrcode = true;
        } else {
          this.isShowQrcode = false;
        }
      } else {
        this.isSelectSpecialSchool = false;
        this.isShowQrcode = false;
      }

      if (this.form.schoolId) {
        this.fetchGoodsList();
      }
    },
    // 选择商品
    onGoodsConfirm(item) {
      this.goodsName = item.text;
      this.form.goodsId = item.value;
      // 商品金额
      this.form.goodsPrice = item.price;
      // 订单金额
      this.form.orderPrice = item.price;
      // 实付金额
      // this.form.actualAmount = item.price;
      this.showGoodsPicker = false;
      console.log("this.form.goodsId", this.form.goodsId);
    },
    // 选择优惠券
    onCouponConfirm(item) {
      // this.form.couponIds = item.value;
      if (!item.value) {
        this.couponName = "";
        let couponId = [];
      } else {
        this.couponName = item.text;
        let couponId = [];
        if (item) {
          couponId.push(item.value);
          this.form.subAmount = item.subAmount;
          this.form.couponIds = Array.from(new Set(couponId));
          this.form.orderPrice = this.form.goodsPrice - item.subAmount;
        } else {
          this.form.couponIds = [];
          this.form.orderPrice = this.form.goodsPrice;
          this.form.subAmount = 0;
        }
      }
      this.showCouponPicker = false;
    },
    //取消优惠券
    onCancel() {
      this.form.couponIds = [];
      this.couponName = "";
      this.form.subAmount = 0;
      this.form.orderPrice = this.form.goodsPrice;
      this.showCouponPicker = false;
    },
    // 查询优惠券
    fetchCoupon(value) {
      this.couponList = [];
      this.flag = true;
      if (this.form.customerPhone) {
        // 获取个人信息
        // this.getUserInfoByPhone();
        getCoupon(this.form.customerPhone).then((res) => {
          if (res.data.code === 200) {
            if (res.data.data) {
              res.data.data.forEach((item) => {
                this.couponList.push({
                  value: item.id,
                  text: item.name,
                  subAmount: item.subAmount,
                });
              });
            }
          } else {
            this.flag = false;
            Toast.fail(res.data.msg);
            setTimeout(() => {
              Toast.clear();
            }, 2000);
          }
        });
      }
    },
    // // 商品改变时
    handleGoods(value) {
      console.log("value", value);
    },
    // 清除优惠券
    handleClear() {
      console.log("clear");
    },

    // 优惠券发生变化时
    handleCoupon(value) {},
    // 车型
    onCarmodelConfirm(item) {
      this.form.carModel = item.value;
      this.carModelName = item.text;
      this.showCarmodelPicker = false;
    },
    // 是否全款
    onIsPayConfirm(item) {
      this.form.payStatus = item.value;
      this.payStateName = item.text;
      this.showIsPayPicker = false;
    },
    // 支付类型
    onPayTypeConfirm(item) {
      this.form.payType = item.value;
      this.payTypeName = item.text;
      this.showPayTypePicker = false;
      if (this.form.payType === "6") {
        this.isSelectOtherPayType = true;
        if (this.isSelectSpecialSchool) {
          this.isShowQrcode = true;
        } else {
          this.isShowQrcode = false;
        }
      } else {
        this.isSelectOtherPayType = false;
        this.isShowQrcode = false;
      }
    },
    onFailed(errorInfo) {
      this.validate = false;
    },
    resetValidation() {
      // 聚焦时重置有效性状态
      this.isValid = true;
    },
    onSubmit(values) {
      this.validate = true;
      if (!this.form.fileIds) {
        Toast("请上传支付凭证");
      } else {
        createOrder(this.form).then((res) => {
          if (res.data.code === 200) {
            Toast.success(res.data.msg);
            this.form = {
              docType: "1",
              qty: 1,
            };
            this.uploader = [];
            this.idcardFileList = [];
            this.goodsName = "";
            this.schoolName = "";
            this.payStateName = "";
            this.payTypeName = "";
          } else {
            Toast.fail(res.data.msg);
          }
        });
      }
    },
  },
};
</script>
<style scoped>
.no-label .van-field__label {
  display: none !important; /* 隐藏 label */
}

.image {
  width: 80px;
  margin-left: -70px;
  margin-top: 10px;
}

::v-deep .input-idCard::after {
  position: absolute;
  box-sizing: border-box;
  content: " ";
  pointer-events: none;
  right: 16px;
  bottom: 0;
  left: 16px;
  border-bottom: 1px solid #ebedf0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}

::v-deep .van-cell__title.van-field__label > span {
  position: relative;
}
::v-deep .required > .van-cell__title.van-field__label > span::before {
  position: absolute;
  right: -8px;
  color: #ee0a24;
  font-size: 14px;
  content: "*";
}
.input-idCard {
  position: relative;
}
::v-deep .icon {
  color: #ee0a24;
  font-size: 14px;
}
::v-deep .upload-pay > .van-cell::after {
  border: none;
}
::v-deep .van-field--error .van-field__control,
.van-field--error .van-field__control::placeholder {
  color: #eee !important;
  -webkit-text-fill-color: currentColor;
}
</style>
